package pl.edu.agh.uddiProxy.server;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import pl.edu.agh.uddiProxy.client.admin.User;
import pl.edu.agh.uddiProxy.client.admin.UserAlreadyExists;
import pl.edu.agh.uddiProxy.client.admin.UserService;
import pl.edu.agh.uddiProxy.dao.DAOHelper;
import pl.edu.agh.uddiProxy.dao.UserDAO;
import pl.edu.agh.uddiProxy.types.Authority;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class UserServiceImpl extends RemoteServiceServlet implements
		UserService {

	private static final long serialVersionUID = -5342502242554267121L;

	private static UserDAO userDAO = DAOHelper.getUserDAO();
	private static Logger logger = Logger.getLogger(UserServiceImpl.class);
	
	public void createUser(User user) throws UserAlreadyExists {
		logger.info("create user " + user.getUsername());
		if (userDAO.exists(user.getUsername())) {
			throw new UserAlreadyExists();
		}
			
		pl.edu.agh.uddiProxy.types.User u = new pl.edu.agh.uddiProxy.types.User(user.getUsername(), user.getFirstName(), user.getLastName(), user.getPassword(), user.getEmail());
		u.addAuthority(Authority.getAuthority(Authority.USER));
		userDAO.create(u);
	}

	public void deleteUser(String username) {
		logger.info("delete user " + username);
		pl.edu.agh.uddiProxy.types.User user = userDAO.loadUserByUsername(username);
		if (!user.isAdministrator()) {
			userDAO.delete(user);
		}
	}

	public User getUserDetails(String username) {
		pl.edu.agh.uddiProxy.types.User u = userDAO.loadUserByUsername(username);
		
		return new User(u.getUsername(), u.getFirstName(), u.getLastName(), u.getPassword(), u.getEmail());
	}

	public List<String> getUsers() {
		List<String> users = new ArrayList<String>();
		for (pl.edu.agh.uddiProxy.types.User u : userDAO.getAll()) {
			users.add(u.getUsername());
		}
		return users;
	}

	public void updateUser(User user) {
		logger.info("update user " + user.getUsername());
		pl.edu.agh.uddiProxy.types.User u = userDAO.loadUserByUsername(user.getUsername());
		u.setEmail(user.getEmail());
		u.setFirstName(user.getFirstName());
		u.setLastName(user.getLastName());
		u.setPassword(user.getPassword());
		userDAO.update(u);
	}

}
